package com.safe.first.application.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RQueue;
import org.redisson.command.CommandAsyncExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author Mickey
 * @since 2022/6/6
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class RedisDelayQueueAppService extends Thread implements Runnable {

    private static final String queueName = "String";
    private final Redisson redisson;
    private final ObjectMapper objectMapper;

    private RDelayedQueue<String> delayedQueue;

    public void add(Integer delay, TimeUnit timeUnit) {
        // 一分钟以后将消息发送到指定队列
        try {
            String hello = objectMapper.writeValueAsString(new TestData("hello"));
            delayedQueue.offer(hello, delay, timeUnit);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    @PostConstruct
    public void init() {
        RQueue<String> queue = redisson.getQueue(queueName);
        CommandAsyncExecutor commandExecutor = redisson.getCommandExecutor();
    }

    @Data
    @AllArgsConstructor
    public static class TestData {

        private String name;

    }

}
